//
//  TTPoint.m
//  iBeaconDemo
//
//  Created by cry on 17/1/9.
//  Copyright © 2017年 eGova. All rights reserved.
//

#import "TTPoint.h"
#import "TTLine.h"

@implementation TTPoint

- (instancetype)initWithX:(double)x Y:(double)y{
    
    return [self initWithX:x Y:y floorName:nil];
}

- (instancetype)initWithX:(double)x Y:(double)y floorName:(NSString *)floorName{
    
    if (self = [super init]) {
        self.x = x;
        self.y = y;
        self.floorName = floorName;
    }
    return self;
}

- (double)distanceWithPoint:(TTPoint *)point{
    
    return point == nil?-1.0:sqrt((self.x - point.x) * (self.x - point.x) + (self.y - point.y) * (self.y - point.y));
}

+ (double)distanceWithPoint1:(TTPoint *)point1 piont2:(TTPoint *)point2{
    return point1 == nil?-1.0:[point1 distanceWithPoint:point2];
}

/**
 * Addition of a point.
 *
 * @param point the point to be added
 * @return a new point
 */
- (TTPoint *)add:(TTPoint *)point{
    return [[TTPoint alloc] initWithX:self.x + point.x
                                    Y:self.y + point.y];
}

/**
 * Negation of the point.
 *
 * @return the negated point
 */
- (TTPoint *)neg{
    return [[TTPoint alloc] initWithX:-self.x
                                    Y:-self.y];
}

/**
 * Subtraction of a point.
 *
 * @param point the point to be subtracted
 * @return a new point
 */
- (TTPoint *)sub:(TTPoint *)point{
    return [self add:[point neg]];
}

/**
 * Cross product (outer product).
 *
 * @param point the second point for the cross product
 * @return the result of the cross product
 */
- (double)cross:(TTPoint *)point{
    return self.x * point.y - self.y * point.x;
}

// TODO make comment (look what this function is doing in detail when time is available)!!!
/**
 *
 *
 * @param p1 the p1
 * @param p2 the p2
 * @return the double
 */
- (double)area2WithPiont1:(TTPoint *)p1 point2:(TTPoint *)p2{
    return [[self sub:p1] cross:[self sub:p2]];
}

/**
 * Checks if the point is located on the right side of the given line.
 *
 * @param l the line for the test
 * @return true, if the point is located on the right side, false otherwise
 */
- (BOOL)isRightOfLine:(TTLine *)l{
    return [self area2WithPiont1:l.startPoint point2:l.endPoint] < 0;
}
/**
 * A string that represents the point.
 *
 * @return string of the point
 */

- (NSString *)description{
    return [NSString stringWithFormat:@"[%.2lf,%.2lf] ",self.x, self.y];
}

@end
